//
//  MyDataViewController.m
//  tuanGG
//
//  Created by 微他 on 15/9/23.
//  Copyright (c) 2015年 weita. All rights reserved.
//

#import "MyDataViewController.h"
#import "MyInformationViewCell.h"
#import "DetailsViewController.h"
#import "PurchaseViewController.h"
#import <MapKit/MapKit.h>
@interface MyDataViewController ()<UITableViewDataSource,UITableViewDelegate,UIActionSheetDelegate>
@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic,strong)UIView *line;
@property (nonatomic,strong)NSArray *array;
@property (nonatomic,strong)NSMutableArray *dataSource;
@property (nonatomic,strong)UIImageView *merchImage;
@property (nonatomic,strong)NSArray *typeArray;
@property (nonatomic,strong)UIView *cityView;
@property (nonatomic,strong)WJCityPikerView *rgisterCity;
@property (nonatomic,strong)NSString *provice;//省
@property (nonatomic,strong)NSString *cityStr;//市级
@property (nonatomic,strong)NSString *districtStr;//区
@property (nonatomic,strong)UITapGestureRecognizer *cityTap;
@property (nonatomic,assign)BOOL isJoin;
@property (nonatomic,strong)NSString *address;
@property (nonatomic,strong)NSString *netAddress;//网络请求地址
@property (nonatomic,strong)NSDictionary *dictionary;//网络请求参数
@end

@implementation MyDataViewController
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if (_isJoin) {
        [self intializeDataSorce];
    }else {
        _isJoin = YES;
    }

}
- (void)viewDidLoad {
    [super viewDidLoad];

 User_member *yy=[User_member instance];

    _typeArray = @[@"火锅",@"中餐",@"西餐",@"汤锅",@"干锅烤鱼",@"快餐",@"小吃",@"烧烤烤肉",@"日韩料理",@"休闲娱乐"];
    [self addnavigationTitle:@"我的资料" navColor:@"4fd2be"];
    [self initView];
    [self addTableView];

    User_member *yyy=[User_member instance];

    [self intializeDataSorce];
    

}
- (void)intializeDataSorce {
    [NSString stringWithFormat:@"%@-%@-%@",[User_member instance].province,[User_member instance].city,[User_member instance].district];
    _dataSource = [[NSMutableArray alloc]initWithObjects:@[[User_member instance].merchname,
                                                           _typeArray[[User_member instance].type-1],
                                                           [User_member instance].helptelephone,
                                                           [NSString stringWithFormat:@"%@-%@-%@",[User_member instance].province,[User_member instance].city,[User_member instance].district],
                                                           [User_member instance].detail],@[@"",@""],@[@"更换",@"修改"], nil];
    [_tableView reloadData];
}
- (void)initView {
    _line = [[UIView alloc]initWithFrame:CGRectMake(0, ScreenHeight/4, ScreenWidth, ScreenHeight/4)];
    _line.backgroundColor =[UIColor whiteColor];
    _merchImage = [[UIImageView alloc]initWithFrame:_line.bounds];
    [_merchImage sd_setImageWithURL:[NSURL URLWithString:[User_member instance].facepic] placeholderImage:nil];
    [_line addSubview:_merchImage];
    UIButton *addImage = [[UIButton alloc]initWithFrame:_line.bounds];
    addImage.backgroundColor = [UIColor clearColor];
    [addImage addTarget:self action:@selector(addImage) forControlEvents:UIControlEventTouchUpInside];
    [_line addSubview:addImage];

}
- (void)addTableView {
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight-20) style:UITableViewStyleGrouped];
    _tableView.contentSize = CGSizeMake(0, 0);
    _tableView.bounces = NO;
    _tableView.tableHeaderView = _line;
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.showsVerticalScrollIndicator = NO;
    [_tableView registerClass:[MyInformationViewCell class] forCellReuseIdentifier:@"CELL"];
    _array = [[NSArray alloc]initWithObjects:@[@"店铺名称",@"店铺类型",@"客服电话",@"所在地区",@"详细地址"],@[@"产品介绍",@"购买须知"],@[@"已绑定手机",@"登录密码"],nil];
    [self.view addSubview:self.tableView];


    //选择城市
    _cityView = [[UIView alloc]initWithFrame:CGRectMake(0, ScreenHeight, ScreenWidth, ScreenHeight-64)];
    _cityView.backgroundColor = RGBACOLOR(138, 138, 136, 0.5);
    _cityView.userInteractionEnabled = YES;
    UITapGestureRecognizer *tapPressed = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(buttonOfPressed)];
    [_cityView addGestureRecognizer:tapPressed];
    [self.view addSubview:_cityView];

    _rgisterCity = [[WJCityPikerView alloc]initWithProvinces:[DatabaseSql queryAllProvinces] city:[DatabaseSql findprovid:@"1" cityID:@"0"] distrct:nil];
    _rgisterCity.isContains = NO;
    _rgisterCity.backgroundColor = RGBACOLOR(236, 235, 232, 1);
    [_cityView addSubview:_rgisterCity];


    NSString *oreillyAddress = @"四川省成都市高新区时代晶科名苑";  //测试使用中文也可以找到经纬度具体的可以多尝试看看~
    CLGeocoder *myGeocoder = [[CLGeocoder alloc] init];
    [myGeocoder geocodeAddressString:oreillyAddress completionHandler:^(NSArray *placemarks, NSError *error) {
        if ([placemarks count] > 0 && error == nil)
        {
            NSLog(@"Found %lu placemark(s).", (unsigned long)[placemarks count]);
            CLPlacemark *firstPlacemark = [placemarks objectAtIndex:0];
            NSLog(@"Longitude = %f", firstPlacemark.location.coordinate.longitude);
            NSLog(@"Latitude = %f", firstPlacemark.location.coordinate.latitude);
        }
        else if ([placemarks count] == 0 && error == nil)
        {
            NSLog(@"Found no placemarks.");
        }
        else if (error != nil)
        {
            NSLog(@"An error occurred = %@", error);
        }
    }];
}
#pragma mark - 事件实现
- (void)addImage {
    UIActionSheet *choiceSheet = [[UIActionSheet alloc] initWithTitle:nil
                                                             delegate:self
                                                    cancelButtonTitle:@"取消"
                                               destructiveButtonTitle:@"拍照"
                                                    otherButtonTitles:@"相册", nil];
    [choiceSheet showInView:self.view];
}
#pragma mark - <选择城市>

- (void)buttonOfPressed {
    [UIView animateWithDuration:0.2 animations:^{
        _cityView.frame = CGRectMake(0, ScreenHeight, ScreenWidth, ScreenHeight-64);
    }];
}
- (void)tapgestureCity {
    [UIView animateWithDuration:0.2 animations:^{
        _cityView.hidden = NO;
        _cityView.frame = CGRectMake(0, 0, ScreenWidth, ScreenHeight-64);
    }];
    [_rgisterCity setModelBlock:^(WJCityPikerModel *model) {
        NSLog(@"%@,%@,%@,%@,%@,%@",model.provinceName,model.provinceId,model.cityId,model.cityName,model.disId,model.disName);
        if (!model.disName) {
            model.disName = @"";
        }
        _provice = model.provinceName;
        _cityStr = model.cityName;
        _districtStr = model.disName;
        _dictionary = @{@"province":_provice,@"city":_cityStr,@"district":_districtStr};

        [UIView animateWithDuration:0.2 animations:^{
            _cityView.frame = CGRectMake(0, ScreenHeight, ScreenWidth, ScreenHeight-64);
        }];
        [self.view endEditing:YES];
        [self netWorking];
    }];
    [_rgisterCity setBackBlock:^{
        [self intializeDataSorce];
        _cityView.hidden = YES;
        
    }];
}
#pragma mark - UITableViewDataSource,UITableViewDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [self.array[section]count];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return  _array.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 10;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MyInformationViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CELL" forIndexPath:indexPath];
    cell.textLabel.text = _array[indexPath.section][indexPath.row];
    cell.textLabel.font = [UIFont systemFontOfSize:14];
    cell.textLabel.textColor = [UIColor colorWithHexString:@"#383838"];
    cell.label.text = _dataSource[indexPath.section][indexPath.row];
    if (indexPath.section == 0 ) {
        cell.accessoryType = UITableViewCellAccessoryNone;
    }else if(indexPath.section == 2){
        cell.label.frame = CGRectMake(ScreenWidth-60, 10, 30, 20);
        if (indexPath.row == 0) {
            NSString *str1 = [[User_member instance].telephone substringToIndex:3];
            NSString *str2 = [[User_member instance].telephone  substringFromIndex:7];
            NSString *str = [NSString stringWithFormat:@"%@****%@",str1,str2];
            cell.phoneNumber.text = str;
            [cell addSubview:cell.phoneNumber];
        }
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }else
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

    return cell;
}
//点击列表事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 0 && indexPath.row == 3) {
        [self tapgestureCity];
    }else if (indexPath.section == 1 && indexPath.row == 1){
        PurchaseViewController *purchaseVC = [[PurchaseViewController alloc]init];
        [self.navigationController pushViewController:purchaseVC animated:YES];
    }else{
    DetailsViewController *detailsVC= [[DetailsViewController alloc]init];
    detailsVC.DetailsArray = [_array mutableCopy];
    detailsVC.typeBlock = ^(NSArray *array) {
    };
    [self.navigationController pushViewController:detailsVC animated:YES];
    detailsVC.title = _array[indexPath.section][indexPath.row];
    detailsVC.string = [NSString stringWithFormat:@"%@",_array[indexPath.section][indexPath.row]];

    }
    NSLog(@"%@",_dictionary);
}
#pragma mark - <UIActionSheetDelegate>

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) {
        NSArray *mediaType = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            _imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
            _imagePicker.mediaTypes = @[mediaType[0]];
            _imagePicker.showsCameraControls = YES;
            _imagePicker.allowsEditing = YES; //允许编辑
            //相机模式
            _imagePicker.cameraCaptureMode = UIImagePickerControllerCameraCaptureModePhoto;
            [self presentViewController:_imagePicker animated:YES completion:nil];
        }else {
            [self addAlert:@"当前设备不支持拍照" otherButtonTitles:nil];
//            [Common showAlertView:@"当前设备不支持拍照"];
        }
    }else if (buttonIndex == 1){
        //获取支持的媒体格式
        NSArray *mediaType =[UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
        
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
            //1.设置图片拾取器的sourceType
            //UIImagePickerControllerSourceTypeSavedPhotosAlbum 显示不同
            _imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            //2.设置支持的媒体格式
            _imagePicker.mediaTypes = @[mediaType[0],mediaType[1]];
            //其它设置
            _imagePicker.allowsEditing = YES; //允许编辑
            [self presentViewController:_imagePicker animated:YES completion:nil];
        }else {
            [self addAlert:@"当前设备不支持拍照" otherButtonTitles:nil];
//            [Common showAlertView:@"当前设备不支持拍照"];
            NSLog(@"不支持");
        }
    }
}
#pragma mark - <UIImagePickerControllerDelegate>
//用户选中了某个媒体
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {

    UIImage *editedImage = info[UIImagePickerControllerEditedImage];
    [self dismissViewControllerAnimated:YES completion:^{
        [self requestOfFruit:[self imageByScalingToMaxSize:editedImage] block:^{
            _merchImage.image = [self imageByScalingToMaxSize:editedImage];

        }];
    }];
}
/**
 *  修改头像
 */
- (void)requestOfFruit:(UIImage *)image block:(dispatch_block_t)block{
    //上个界面没有传id
    NSMutableDictionary *dic=[[NSMutableDictionary alloc] init];
    NSMutableDictionary *dicImage = [[NSMutableDictionary alloc]init];
    [dicImage setObject:image forKey:@"facepic"];
    [GLAFRequest startFileRequest:alterMydataPoto time:20 isTouch:YES paramsDic:dic defaultdialog:YES picDic:dicImage handleSuccess:^(id sta, NSDictionary *paramsDic) {
        NSLog(@"信息：%@",sta);
        if ([sta[@"code"]integerValue] == 1) {
            //清除图片缓存
            [[SDWebImageManager sharedManager].imageCache clearDisk];
            [Common deleteNSUserDefaults:Setting_headimgae_url];
            [Common addAlert:@"修改头像成功"];
            [_tableView reloadData];
            block();
        }
    } netWorkFail:^(NSDictionary *paramsDic) {

    }];
}
#pragma mark - 网络请求
- (void)netWorking {
    [GLAFRequest startRequest:address_url paramsDic:_dictionary defaultdialog:YES ispost:YES handleSuccess:^(id sta, NSDictionary *paramsDic) {
        NSLog(@"%@",sta);
        if ([sta[@"code"]integerValue ] == 1) {
            [Common addAlert:@"修改成功"];
            [self intializeDataSorce];
        }
    } doFinally:^(NSDictionary *paramsDic) {

    }];

}
@end

